package top.myliangsl.newsapplets.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import top.myliangsl.newsapplets.domain.po.TNews;
import top.myliangsl.newsapplets.domain.po.jdApi.JdNewsDto;
import top.myliangsl.newsapplets.mapper.TNewsMapper;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 新闻频道列表
 *
 * @author xiaoliang
 */
@Service
@Slf4j
public class TNewsService extends ServiceImpl<TNewsMapper, TNews> {

    public void insertNewsChannel(String channelName, List<JdNewsDto.ListDTO> dto) {
        List<String> titleList = dto.stream().map(JdNewsDto.ListDTO::getTitle).collect(Collectors.toList());

        QueryWrapper<TNews> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("title", titleList);
        List<TNews> newsList = baseMapper.selectList(queryWrapper);

        Map<String, TNews> dtoMap = null;
        if (!CollectionUtils.isEmpty(newsList)) {
            dtoMap = newsList.stream().collect(Collectors.toMap(TNews::getTitle, Function.identity()));
        }
        Map<String, TNews> finalDtoMap = dtoMap;
        List<TNews> tNews = dto.stream().parallel()
                .filter(dt -> !CollectionUtils.isEmpty(finalDtoMap) && Objects.isNull(finalDtoMap.get(dt.getTitle())))
                .map(listDTO -> TNews.builder()
                        .title(listDTO.getTitle())
                        .category(listDTO.getCategory())
                        .content(listDTO.getContent())
                        .publishTime(listDTO.getTime())
                        .src(listDTO.getSrc())
                        .pic(listDTO.getPic())
                        .channelName(channelName)
                        .created(System.currentTimeMillis())
                        .url(listDTO.getUrl())
                        .webUrl(listDTO.getWeburl())
                        .build()).collect(Collectors.toList());
        saveBatch(tNews);
    }
}
